import {Command} from '../constant';
import {Dispatch} from 'typings';
import {IAllReducerProps} from '../types';
import {getReducerData} from '@/redux/store';
import api from 'api';
import {extraPathsValue} from '@/redux/util';
import Taro from '@tarojs/taro';

export default (dispatch: Dispatch) => {
  let action = {
    commonChange(...param: any) {
      dispatch({
        type: Command.commonChange,
        payload: extraPathsValue(...arguments),
      });
    },

    async page() {
      let userInfo = Taro.getStorageSync('b2b-wechat@login').user;
      const res = await Promise.all([
        api.shopController.findOrderCount({}), //查询订单角标
        api.pointsMallController.findCustomerInfo(), //获取用户积分信息
        api.customerSignRecordController.getCustomerInfo(), //查询用户信息
        api.customerBaseController.findCustomerBaseInfo(), // 会员信息
        api.mobileConfigController.findCustomerblacklist({customerMobile: userInfo.phone}), //查询黑名单
      ]);
      Taro.setStorageSync('blacklistModel', res[4].content.length > 0 ? true : false);
      action.commonChange([
        {paths: 'main.orderCount', value: res[0]},
        {paths: 'main.pointsAvailable', value: res[1] && res[1].pointsAvailable ? res[1].pointsAvailable : null},
        {paths: 'main.totalSignDays', value: res[2].customerVO.totalSignDays},
        {paths: 'main.isAquamarineMember', value: res[3].isAquamarineMember},
        {paths: 'main.isCrystalMember', value: res[3].isCrystalMember},
        {paths: 'main.memberDays', value: res[3].memberDays},
        {paths: 'main.endTime', value: res[3].endTime},
        {paths: 'main.dualMembershipCardNumber', value: res[3].dualMembershipCardNumber},
        {paths: 'main.aquamarineMembershipCardNumber', value: res[3].aquamarineMembershipCardNumber},
        {paths: 'main.crystalMembershipCardNumber', value: res[3].crystalMembershipCardNumber},
        {paths: 'main.rankBadgeImg', value: res[3].rankBadgeImg},
        {paths: 'main.blacklistModel', value: res[4].content.length > 0 ? true : false},
      ]);
    },

    async changeInfo(headPicture, customerName) {
      try {
        if (headPicture) {
          await api.wechatLoginController.modify({headPicture});
        }
        if (customerName) {
          await api.wechatLoginController.modify({customerName});
        }
        let customer = await api.wechatLoginController.getUserInfo();
        if (!customer) {
          // 获取不到用户信息 可能是版本更替 需清除登录
          Taro.removeStorageSync('b2b-wechat@login');
          Taro.removeStorageSync('authInfo:token');
        }
        action.commonChange('main.customer', JSON.parse(JSON.stringify(customer)));
      } catch (error) {
        console.log(error);
        Taro.showToast({title: '操作失败', icon: 'none'});
      }
    },
  };
  return action;
};

function getData(): IAllReducerProps {
  return {
    main: getReducerData('packageUserCenterMain'),
  };
}

//create by moon https://github.com/creasy2010/moon
